#include "GX21M15.h"
#include <ACM32Fxx_HAL.h>
#include <rtthread.h>
I2C_HandleTypeDef I2C_Handle;
#define SLAVE_ADDRESS    (0x91)
void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
{
    /*
      NOTE : This function should be modified by the user.
    */

    /* For Example */
    GPIO_InitTypeDef GPIO_Handle;

    /* I2C1 */
    if (hi2c->Instance == I2C1)
    {
        /* Enable Clock */
        System_Module_Reset(RST_I2C1);
        System_Module_Enable(EN_I2C1);
        System_Module_Enable(EN_GPIOAB);

        /* I2C1 SDA  PortB Pin7 */
        /* I2C1 SCL  PortB Pin6 */
        GPIO_Handle.Pin = GPIO_PIN_6 | GPIO_PIN_7;
        GPIO_Handle.Mode = GPIO_MODE_AF_OD;
        GPIO_Handle.Pull = GPIO_PULLUP;
        GPIO_Handle.Alternate = GPIO_FUNCTION_6;
        HAL_GPIO_Init(GPIOB, &GPIO_Handle);

        /* Clear Pending Interrupt */
        NVIC_ClearPendingIRQ(I2C1_IRQn);

        /* Enable External Interrupt */
        NVIC_EnableIRQ(I2C1_IRQn);
    }
    /* I2C2 */
    else if (hi2c->Instance == I2C2)
    {
        System_Module_Reset(RST_I2C2);
        System_Module_Enable(EN_I2C2);
        System_Module_Enable(EN_GPIOCD);

        /* I2C2 SDA  PortD Pin7 */
        /* I2C2 SCL  PortD Pin6 */
        GPIO_Handle.Pin = GPIO_PIN_6 | GPIO_PIN_7;
        GPIO_Handle.Mode = GPIO_MODE_AF_OD;
        GPIO_Handle.Pull = GPIO_PULLUP;
        GPIO_Handle.Alternate = GPIO_FUNCTION_1;
        HAL_GPIO_Init(GPIOD, &GPIO_Handle);

        /* Clear Pending Interrupt */
        NVIC_ClearPendingIRQ(I2C2_IRQn);

        /* Enable External Interrupt */
        // NVIC_EnableIRQ(I2C2_IRQn);
    }
}
int gx21m15h_get_temp(float *temp)
{
    int ret = 0;
    uint8_t rxbuf[2] = {0};
    uint16_t rxData = 0;
    uint16_t temp_mask = 0x3ff;

    if (HAL_I2C_Master_Receive(&I2C_Handle, SLAVE_ADDRESS, rxbuf, 2, 10000) == HAL_OK)
    {
        rxData = (rxbuf[0] << 8) + rxbuf[1];
        rxData >>= 5;
        if (rxData & 0x400)
        {

            rxData = (~rxData);
            rxData &= temp_mask;
            rxData += 1;
            *temp = (-rxData) * 0.125;
        }
        else
        {
            *temp = rxData * 0.125;
        }
    }
    else
    {
        ret = -1;
    }
    return ret;
}
void I2C_Init(void)
{

    I2C_Handle.Instance = I2C2;
    I2C_Handle.Init.I2C_Mode = I2C_MODE_MASTER;
    I2C_Handle.Init.Tx_Auto_En = TX_AUTO_EN_ENABLE;
    I2C_Handle.Init.Clock_Speed = CLOCK_SPEED_STANDARD;
    I2C_Handle.Init.No_Stretch_Mode = NO_STRETCH_MODE_NOSTRETCH;

    HAL_I2C_Init(&I2C_Handle);
}
int gx21m15h_init(void)
{
    I2C_Init();
    return 0;
}
INIT_BOARD_EXPORT(gx21m15h_init);
